package delayMessage.cycle;

import delayMessage.queue.JobCallBack;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 延迟消息
 * <p>
 * 两个重要的数据结构
 * 1.环形队列，例如可以创建一个包含3600个slot的环形队列（本质是个数组）
 * 2.任务集合，环上每一个slot是一个Set
 * <p>
 * timer 计时器每1秒往后一格，同时执行该格上的任务集合
 * <p>
 * <p>
 * Created by Zhou_Bing on 2018/9/29.
 */
public class DelayCycleTest {

    public static void main(String[] args){

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

        DelayCycle delayCycle = new DelayCycle(3600);

        delayCycle.add(2, new JobCallBack() {
            @Override
            public void execute() {
                System.out.println("hello");
            }
        });
        delayCycle.add(4, new JobCallBack() {
            @Override
            public void execute() {
                System.out.println("world");
            }
        });

        final int[] curIndex = {0};
        final int[] cycleNum = {0};
        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Set<Job> jobs = delayCycle.get(curIndex[0]);

                if(jobs!=null){
                    fixedThreadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                            jobs.forEach(j->{
                                if(Integer.compare(j.getCycleNum(),cycleNum[0])==0){
                                    j.execute();
                                }
                            });
                        }
                    });
                }
                curIndex[0] = (curIndex[0] +1)%delayCycle.length();
            }
        },0,1000);
    }
}
